package cn.exrick.sso.service.impl;

import cn.exrick.common.exception.XmallException;
import cn.exrick.manager.mapper.TbAddressMapper;
import cn.exrick.manager.pojo.TbAddress;
import cn.exrick.manager.pojo.TbAddressExample;
import cn.exrick.sso.service.AddressService;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private TbAddressMapper tbAddressMapper;

    @Override
    public List<TbAddress> getAddressList(Long userId) {

        TbAddressExample example=new TbAddressExample();
        TbAddressExample.Criteria criteria=example.createCriteria();
        criteria.andMemberIdEqualTo(userId);
        example.setOrderByClause("is_default desc");
        List<TbAddress> list=tbAddressMapper.selectByExample(example);
        return list;
    }

    @Override
    public TbAddress getAddress(Long addressId) {

        TbAddress tbAddress=tbAddressMapper.selectByPrimaryKey(addressId);
        if(tbAddress==null){
            throw new XmallException("通过id获取地址失败");
        }
        return tbAddress;
    }

    @Override
    public int addAddress(TbAddress tbAddress) {

        //设置唯一默认
        setOneDefault(tbAddress);
        if(tbAddressMapper.insert(tbAddress)!=1){
            throw new XmallException("添加地址失败");
        }
        return 1;
    }

    @Override
    public int updateAddress(TbAddress tbAddress) {
        //设置唯一默认
        setOneDefault(tbAddress);
        if(tbAddressMapper.updateByPrimaryKeySelective(tbAddress)!=1){
            throw new XmallException("更新地址失败");
        }
        return 1;
    }

    @Override
    public int delAddress(Long id) {

        if(tbAddressMapper.deleteByPrimaryKey(id)!=1){
            throw new XmallException("删除地址失败");
        }
        return 1;
    }

    public void setOneDefault(TbAddress tbAddress){
        //设置唯一默认
        if(tbAddress.getIsDefault()){
            TbAddressExample example=new TbAddressExample();
            TbAddressExample.Criteria criteria= example.createCriteria();
            criteria.andMemberIdEqualTo(tbAddress.getMemberId());
            criteria.andIsDefaultEqualTo((byte) 1);
            List<TbAddress> list=tbAddressMapper.selectByExample(example);
            if(CollectionUtils.isNotEmpty(list)){
                TbAddress address = list.get(0);
                address.setIsDefault(false);
                tbAddressMapper.updateByPrimaryKey(address);
            }
        }
    }
}
